package vip.george.p0976;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class P976 {


    public int largestPerimeter(int[] nums) {
        int len = nums.length;
        if (len < 3) {
            return 0;
        }
        List<Integer> list = Arrays.stream(nums).boxed().sorted(Comparator.reverseOrder()).toList();
        for (int i = 0; i < len - 2; i++) {
            //判断是否满足三角形条件（较小的两边和大于最大边）
            if (list.get(i) < list.get(i + 1) + list.get(i + 2)) {
                return list.get(i) + list.get(i + 1) + list.get(i + 2);
            }
        }
        return 0;
    }


    /**
     * 和方法1逻辑相同，仅仅是数组升序，需要从后往前遍历
     * @param nums
     * @return
     */
    public int largestPerimeter2(int[] nums) {
        int len = nums.length;
        if (len < 3) {
            return 0;
        }
        Arrays.sort(nums);
        for (int i = len - 1; i >= 2; i--) {
            //判断是否满足三角形条件（较小的两边和大于最大边）
            if (nums[i - 2] + nums[i - 1] > nums[i]) {
                return nums[i - 2] + nums[i - 1] + nums[i];
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        P976 p976 = new P976();
        System.out.println(p976.largestPerimeter2(new int[]{2, 1, 5, 0, 4, 6}));
        System.out.println(p976.largestPerimeter2(new int[]{3, 6, 2, 3}));
    }


}
